<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.sku" placeholder="货号" clearable style="width: 160px;" class="filter-item" />
      <el-select v-model="listQuery.brandId" placeholder="品牌" clearable filterable style="width: 300px; margin-left: 10px;" class="filter-item">
        <el-option v-for="item in brandOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.goodsCategory" placeholder="大类" clearable filterable style="width: 140px; margin-left: 10px;" class="filter-item">
        <el-option v-for="item in goodsCategoryOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.year" placeholder="年份" clearable filterable style="width: 140px; margin-left: 10px;" class="filter-item">
        <el-option v-for="item in yearOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.season" placeholder="季节" clearable filterable style="width: 140px; margin-left: 10px;" class="filter-item">
        <el-option v-for="item in seasonOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.goodsSex" placeholder="性别" clearable filterable style="width: 140px; margin-left: 10px;" class="filter-item">
        <el-option v-for="item in goodsSexOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" style="margin-left: 10px;" type="info" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="info" icon="el-icon-refresh" @click="handleRefresh">
        重置
      </el-button>
      <router-link :to="'/manager/goods/product/add/'">
        <el-button class="filter-item" style="margin-left: 10px;" type="info" icon="el-icon-circle-plus-outline">
          添加
        </el-button>
      </router-link>
      <el-upload
        v-loading="uploadLoading"
        class="avatar-uploader filter-item"
        action="#"
        :show-file-list="false"
        :before-upload="beforeProductUpload"
        :http-request="productUpload"
        style="margin-left: 10px;"
      >
        <el-button type="info" icon="el-icon-upload">
          上传
        </el-button>
      </el-upload>
      <el-button :loading="downloadTemplateLoading" class="filter-item" style="margin-left: 10px;" type="info" icon="el-icon-document" @click="handleDownloadTemplate">
        模板下载
      </el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" :header-cell-style="headerCellStyle" border stripe element-loading-text="拼命加载中">
      <el-table-column label="货号" align="center" min-width="160px">
        <template slot-scope="{row}">
          <span style="float: left;">{{ row.sku }}</span>
        </template>
      </el-table-column>
      <el-table-column label="品牌" align="center" width="300px">
        <template slot-scope="{row}">
          <span style="float: left;">{{ row.brandId | brandFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="产品名称" align="center" min-width="110px">
        <template slot-scope="{row}">
          <span style="float: left;">{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="大类" align="center" width="50px">
        <template slot-scope="{row}">
          <span>{{ row.goodsCategory | goodsCategoryFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="中类" align="center" min-width="110px">
        <template slot-scope="{row}">
          <span style="float: left;">{{ row.series }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年份" align="center" width="60px">
        <template slot-scope="{row}">
          <span>{{ row.year | yearFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="季节" align="center" width="50px">
        <template slot-scope="{row}">
          <span>{{ row.season | seasonFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" width="50px">
        <template slot-scope="{row}">
          <span>{{ row.goodsSex | goodsSexFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="颜色" align="center" min-width="110px">
        <template slot-scope="{row}">
          <span style="float: left;">{{ row.color }}</span>
        </template>
      </el-table-column>
      <el-table-column label="重量(KG)" align="center" width="80px">
        <template slot-scope="{row}">
          <span style="float: right;">{{ row.weight }}</span>
        </template>
      </el-table-column>
      <el-table-column label="吊牌价" align="center" width="70px">
        <template slot-scope="{row}">
          <span style="float: right;">{{ row.marketPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="卖点" align="center" min-width="110px">
        <template slot-scope="{row}">
          <span style="float: left;">{{ row.saleProps }}</span>
        </template>
      </el-table-column>
      <el-table-column label="材质" align="center" min-width="110px">
        <template slot-scope="{row}">
          <span style="float: left;">{{ row.material }}</span>
        </template>
      </el-table-column>
      <el-table-column label="细节备注" align="center" min-width="110px">
        <template slot-scope="{row}">
          <span style="float: left;">{{ row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="140px" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <router-link :to="'/manager/goods/product/'+row.id+'/edit'">
            <el-button type="info" size="mini">
              编辑
            </el-button>
          </router-link>
          <el-button type="danger" size="mini" style="margin-left: 5px;" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize" @pagination="getList" />

  </div>
</template>

<script>
import { Message } from 'element-ui'
import { fetchEnum } from '@/api/system-api'
import { getProductByPage, deleteProductById } from '@/api/manager/goods-api'
import { downloadProduct, uploadProduct, downloadProductTemplate } from '@/api/manager/goods-api'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import { toOptionsList, toKeyValueMap, handleDownloadWithUtf8Filename } from '@/utils/index'

var brandKeyValue = {}
var goodsCategoryKeyValue = {}
var yearKeyValue = {}
var seasonKeyValue = {}
var goodsSexKeyValue = {}

export default {
  name: 'ManagerProduct',
  components: { Pagination },
  directives: { waves },
  filters: {
    brandFilter(brand) {
      return brandKeyValue[brand]
    },
    goodsCategoryFilter(goodsCategory) {
      return goodsCategoryKeyValue[goodsCategory]
    },
    yearFilter(year) {
      return yearKeyValue[year]
    },
    seasonFilter(season) {
      return seasonKeyValue[season]
    },
    goodsSexFilter(goodsSex) {
      return goodsSexKeyValue[goodsSex]
    }
  },
  data() {
    return {
      beforeRouteEnterNextIgnore: true,

      brandOptions: [],
      goodsCategoryOptions: [],
      yearOptions: [],
      seasonOptions: [],
      goodsSexOptions: [],
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        sku: null,
        brandId: null,
        goodsCategory: null,
        year: null,
        season: null,
        goodsSex: null
      },
      downloadLoading: false,
      uploadLoading: false,
      downloadTemplateLoading: false,

      listLoading: true,
      list: null,
      total: 0

    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (!vm.beforeRouteEnterNextIgnore) {
        vm.getList()
      } else {
        vm.beforeRouteEnterNextIgnore = false
      }
    })
  },
  async created() {
    await this.initLoad()
    await this.getList()
  },
  methods: {
    async initLoad() {
      const dataDictsParam = ['BRAND', 'GOODS_CATEGORY', 'YEAR', 'SEASON', 'GOODS_SEX']
      const { data } = await fetchEnum(dataDictsParam)
      for (const dataDict of data) {
        if (dataDict.code === 'BRAND') {
          if (dataDict.options) {
            this.brandOptions = toOptionsList(dataDict.options, 'id', 'name')
            brandKeyValue = toKeyValueMap(this.brandOptions, 'key', 'display_name')
          }
        } else if (dataDict.code === 'GOODS_CATEGORY') {
          if (dataDict.options) {
            this.goodsCategoryOptions = toOptionsList(dataDict.options, 'code', 'name')
            goodsCategoryKeyValue = toKeyValueMap(this.goodsCategoryOptions, 'key', 'display_name')
          }
        } else if (dataDict.code === 'YEAR') {
          if (dataDict.options) {
            this.yearOptions = toOptionsList(dataDict.options, 'code', 'name')
            yearKeyValue = toKeyValueMap(this.yearOptions, 'key', 'display_name')
          }
        } else if (dataDict.code === 'SEASON') {
          if (dataDict.options) {
            this.seasonOptions = toOptionsList(dataDict.options, 'code', 'name')
            seasonKeyValue = toKeyValueMap(this.seasonOptions, 'key', 'display_name')
          }
        } else if (dataDict.code === 'GOODS_SEX') {
          if (dataDict.options) {
            this.goodsSexOptions = toOptionsList(dataDict.options, 'code', 'name')
            goodsSexKeyValue = toKeyValueMap(this.goodsSexOptions, 'key', 'display_name')
          }
        }
      }
      this.initListQuery()
    },
    getList() {
      this.listLoading = true
      getProductByPage(this.listQuery).then(response => {
        const { data } = response
        this.list = data.result
        this.total = data.totalCount
        setTimeout(() => {
          this.listLoading = false
        }, 1 * 1000)
      }).catch(error => {
        Message({
          message: error,
          type: 'error',
          duration: 5 * 1000
        })
        this.listLoading = false
      })
    },
    initListQuery() {
      this.listQuery = {
        pageNo: 1,
        pageSize: 20,
        sku: null,
        brandId: null,
        goodsCategory: null,
        year: null,
        season: null,
        goodsSex: null
      }
    },

    handleFilter() {
      this.getList()
    },
    handleDownload() {
      this.downloadLoading = true
      downloadProduct(this.listQuery).then(response => {
        handleDownloadWithUtf8Filename(response)
        this.downloadLoading = false
      }).catch(error => {
        Message({
          message: error,
          type: 'error',
          duration: 5 * 1000
        })
        this.downloadLoading = false
      })
    },
    handleRefresh() {
      this.initListQuery()
      this.getList()
    },
    beforeProductUpload(file) {
      var pass = true
      return pass
    },
    productUpload(param, type) {
      this.uploadLoading = true
      var formData = new FormData()
      formData.append('file', param.file)
      uploadProduct(formData).then(response => {
        if (response && response.data && response.data.productCount) {
          Message({
            message: '成功上传商品信息' + response.data.productCount + '条',
            type: 'success',
            duration: 5 * 1000
          })
          this.handleRefresh()
        } else {
          Message({
            message: response.msg,
            type: 'error',
            duration: 5 * 1000
          })
        }
        this.uploadLoading = false
      }).catch(error => {
        if (error) {
          Message({
            message: error,
            type: 'error',
            duration: 5 * 1000
          })
        } else {
          Message({
            message: '文件上传失败',
            type: 'error',
            duration: 5 * 1000
          })
        }
        this.uploadLoading = false
      })
    },
    handleDownloadTemplate() {
      this.downloadTemplateLoading = true
      downloadProductTemplate().then(response => {
        handleDownloadWithUtf8Filename(response)
        this.downloadTemplateLoading = false
      }).catch(error => {
        Message({
          message: error,
          type: 'error',
          duration: 5 * 1000
        })
        this.downloadTemplateLoading = false
      })
    },
    headerCellStyle({ row, rowIndex }) {
      return 'background-color: #42b983; color: #FFF;'
    },
    handleDelete(row) {
      deleteProductById(row.id).then(response => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      }).catch(error => {
        Message({
          message: error,
          type: 'error',
          duration: 5 * 1000
        })
      })
    }

  }
}

</script>
